import 'package:ai_extinguisher/const/const.dart';
import 'package:ai_extinguisher/modules/home/slider.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'home_controller.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> with WidgetsBindingObserver {
  final controller = Get.find<HomeController>();
  final id_textcontroller = TextEditingController();
  final mac_textcontroller = TextEditingController();
  double _keyboardHeight = 0.0;

  @override
  void initState() {
    super.initState();
    id_textcontroller.text = '';
    mac_textcontroller.text = '';
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeMetrics() {
    final bottomInset = WidgetsBinding.instance.window.viewInsets.bottom;
    // 说明键盘从弹出 -> 收起
    if (_keyboardHeight > 0 && bottomInset == 0) {
      FocusScope.of(context).unfocus();
    }
    // 说明键盘从收起 -> 弹出
    else if (_keyboardHeight == 0 && bottomInset > 0) {}
    // 更新当前记录
    _keyboardHeight = bottomInset;
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    final mediaQuery = MediaQuery.of(context);
    final screenHeight = mediaQuery.size.height; // 屏幕总高度
    final statusBarHeight = mediaQuery.padding.top; // 状态栏高度
    const bottomBarHeight = kBottomNavigationBarHeight; // 底部系统导航栏高度
    final contentHeight = screenHeight - statusBarHeight;
    return Scaffold(
      appBar: null,
      backgroundColor: bgColor,
      body: SafeArea(
        child: SingleChildScrollView(
          child: FocusScope(
            child: GestureDetector(
              onTap: () => FocusScope.of(context).unfocus(),
              child: Container(
                height: contentHeight,
                padding: EdgeInsets.all(30),
                child: Column(
                  spacing: 20,
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    ///
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Expanded(
                          child: Text(
                            '智能灭火器状态',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                              letterSpacing: 10,
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 25,
                          height: 25,
                          child: InkWell(
                            splashColor: Colors.white,
                            hoverColor: Colors.white,
                            highlightColor: Colors.white,
                            child: Image.asset(assets.refresh_select),
                            onTap: () {
                              controller.refresh();
                            },
                          ),
                        ),
                      ],
                    ),

                    ///
                    Container(
                      width: size.width - 40,
                      height: 120,
                      padding: const EdgeInsets.only(right: 5, top: 5, bottom: 5),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        border: Border.all(color: Colors.white, width: 1),
                        borderRadius: BorderRadius.circular(20),
                        boxShadow: const [BoxShadow(color: Colors.black, offset: Offset(0, 0), blurRadius: 10)],
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: List.generate(['ID', 'MAC'].length * 2 - 1, (index) {
                          // 偶数下标放 Row，奇数下标放 Divider
                          if (index.isOdd) {
                            return Divider(color: Colors.grey, thickness: 1, height: 1);
                          }
                          final label = ['ID', 'MAC'][index ~/ 2];
                          return Row(
                            children: [
                              Container(
                                width: 60,
                                child: Text(
                                  '$label: ',
                                  style: const TextStyle(color: Colors.black, fontSize: 18),
                                  textAlign: TextAlign.right,
                                ),
                              ),
                              Expanded(
                                child: Obx(() {
                                  mac_textcontroller.text = controller.mac.value;
                                  return TextField(
                                    controller: label == 'ID' ? id_textcontroller : mac_textcontroller,
                                    textAlign: TextAlign.center,
                                    readOnly: label != 'ID',
                                    style: const TextStyle(
                                      fontSize: 20,
                                      fontWeight: FontWeight.w600,
                                      color: Colors.black,
                                    ),
                                    decoration: const InputDecoration(
                                      contentPadding: EdgeInsets.symmetric(vertical: 0),
                                      enabledBorder: InputBorder.none,
                                      focusedBorder: InputBorder.none,
                                      border: InputBorder.none,
                                    ),
                                    onChanged: (value) {
                                      controller.updateIDorMac(id_textcontroller.text, mac_textcontroller.text);
                                    },
                                    onSubmitted: (value) {
                                      controller.updateIDorMac(id_textcontroller.text, mac_textcontroller.text);
                                    },
                                    onEditingComplete: () {
                                      controller.updateIDorMac(id_textcontroller.text, mac_textcontroller.text);
                                    },
                                  );
                                }),
                              ),
                            ],
                          );
                        }),
                      ),
                    ),

                    ///图片
                    Flexible(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        spacing: 20,
                        children: [
                          Flexible(flex: 2, child: Image.asset(assets.fire)),
                          Flexible(
                            child: Container(
                              color: Colors.transparent,
                              child: Obx(() {
                                return HomeItem(value: double.parse(controller.pressure.value));
                              }),
                            ),
                          ),
                        ],
                      ),
                    ),

                    ///
                    Obx(() {
                      var text = controller.rssi.value.isEmpty
                          ? ''
                          : 'rssi:${controller.rssi.value}  Company:<0x${controller.company_key.value}> 0x${controller.company_value.value} Details: 0x${controller.msd.value} EDR:(${controller.mac.value}) 电量:${controller.electricity}%';

                      return SizedBox(
                        height: 130,
                        child: Stack(
                          children: [
                            Positioned(
                              top: 0,
                              left: 0,
                              right: 0,
                              height: 30,
                              child: Center(
                                child: FittedBox(
                                  fit: BoxFit.scaleDown, // 缩小而不是放大
                                  alignment: Alignment.centerLeft,
                                  child: Text(text, maxLines: 2),
                                ),
                              ),
                            ),

                            Positioned(
                              left: 0,
                              right: 0,
                              bottom: 0,
                              top: 30,
                              child: Container(
                                width: size.width - 40,
                                height: 100,
                                decoration: BoxDecoration(
                                  color: Color(0xFFAE2B26),
                                  border: BoxBorder.all(color: Colors.white, width: 1),
                                  borderRadius: BorderRadius.circular(20),
                                  boxShadow: [BoxShadow(color: Colors.white, offset: Offset(0, 0), blurRadius: 10)],
                                ),
                                child: Center(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                                    children: ['压力', "温度"].asMap().entries.map(($0) {
                                      var list = [controller.pressure.value, controller.temp2.value];
                                      return Column(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                          Text(
                                            '${list[$0.key]} ${$0.key == 0 ? 'Mpa' : '°C'}',
                                            style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                                          ),
                                          Text($0.value),
                                        ],
                                      );
                                    }).toList(),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      );
                    }),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
